//The console UI
(function($) {
	$.console = function(element, options) {
		// To avoid scope issues, use 'base' instead of 'this'
		// to reference this class from internal events and functions.
		var base = this;
		
		// Access to jQuery and DOM versions of element
		base.$element = $(element);
		base.element = element;

		base.init = function() {
			base.options = $.extend({}, $.console.defaultOptions, options);
			base.$element.append(
			"<div class='console-window' >" +
				"<div class='console-header'>" +
					"<div class='console-clear console-left'>" +
						"<a class='console-clear-link' href='#'>Clear</a>" +
					"</div>" +
					"<div class='console-iconify console-rigth'>" +
						"<a class='console-iconify-link' href='#'>-</a>" +
					"</div>" +
				"</div>" +
				"<div class = 'console-content'></div>"+
			"</div>"
			);
			
			$(".console-iconify-link").toggle(
				function(){
					$(this).parents(".console-window").removeClass("console-window")
							.addClass("console-window-iconified");
				},
				function(){
					$(this).parents(".console-window-iconified").removeClass("console-window-iconified")
							.addClass("console-window");
				}
			);
			
			$(".console-clear-link").click(function(){
				base.$element.console("clear", 1);
			});
			
		};
		
		// Run initializer
		base.init();
	};
	
	$.consoleCalls = function(element, call, param){
		var $content = $(element).find(".console-content");
		
		switch(call){
			case "print": $content.append(param);
				break;
			case "println": $content.append(param + "<br />");
				break;
			case "clear": $content.text("");
				break;
		}
	}

	$.console.defaultOptions = {};
	
	$.fn.console = function(options) {
		var arg = arguments[1]; 
		if(arguments.length === 2){
			return this.each(function() {
				(new $.consoleCalls(this, options, arg));
			});
		}else{
			return this.each(function() {
				(new $.console(this, options));
			});		
		}		
	};
	
})(jQuery);

function Console(element){
	base = this;
	$(element).console();
	
	base.$element = $(element);
	
	this.print = function(text){
		base.$element.console("print", text);
	}
	
	this.println = function(text){
		base.$element.console("println", text);
	}
	
	this.clear = function(){
		base.$element.console("clear", 1);
	}
}

var out;

$(document).ready(function(){
	out = new Console(document.body);
});
